package com.woniuxy.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.xdevapi.JsonArray;
import com.woniuxy.dto.ManagerDto;
import com.woniuxy.entity.JsonUser;
import com.woniuxy.entity.RbacManagerEntity;
import com.woniuxy.service.RbacManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @Author: ideaAdmin
 * TODO:
 * Date: 2022/2/14:18:38
 * Description:
 */
@Controller
@RequestMapping("/rbacManager")
public class RbacManagerController {
    @Autowired
    private RbacManagerService rbacManagerService;

    @RequestMapping("/findAll")
    @ResponseBody
    public ManagerDto<List<RbacManagerEntity>> getManagerAll() {
        List<RbacManagerEntity> all = rbacManagerService.findAll();
        ManagerDto<List<RbacManagerEntity>> listManagerDto = new ManagerDto<>();

        listManagerDto.setCode(200);

        listManagerDto.setData(rbacManagerService.findAll());
        return listManagerDto;
    }

    @RequestMapping("/addManager")
    @ResponseBody
    public ManagerDto<Integer> addManager(@RequestBody @Valid RbacManagerEntity rbacManagerEntity, BindingResult bindingResult) {
        ManagerDto<Integer> dto = new ManagerDto<>();
        if (bindingResult.hasErrors()) {
            dto.setCode(500);
            FieldError fieldError = bindingResult.getFieldError();
            dto.setMessage(fieldError.getField() + fieldError.getDefaultMessage());
            return dto;
        }

        if (rbacManagerService.addManager(rbacManagerEntity)) {
            dto.setCode(200);
            dto.setMessage("成功");
            dto.setData(rbacManagerEntity.getId());
        } else {
            dto.setCode(500);
            dto.setMessage("不能为空");
        }
        return dto;
    }


    @RequestMapping("/addJson")
    @ResponseBody
    public ManagerDto addJson(@RequestBody JSONObject JSONObject) {

        ManagerDto<Object> dto = new ManagerDto<>();
        dto.setData(JSONObject);
        System.out.println(JSONObject.toJSONString());
        JsonUser jsonUser = new JsonUser();
        jsonUser.setData(JSONObject.toJSONString());
        if (rbacManagerService.addJson(jsonUser)) {

        }
        return dto;
    }

    @GetMapping("/find/{id}")
    @ResponseBody
    public ManagerDto<List<JsonUser>> findAll(@PathVariable Integer id) {
        ManagerDto<List<JsonUser>> dto = new ManagerDto<>();
        System.out.println(id);
        List<JsonUser> byId = rbacManagerService.findById();
        for(JsonUser jsonUser:byId){
            Object o = JSONObject.toJSON(jsonUser);
            System.out.println(o);
        }
        dto.setData(byId);

        return dto;
    }
}
